<?php
function path2dirfile($path, $mkdir = false, $dir = DATA_DIR) {
	$path = trim($path);
	$path_segments = explode("/", $path);
	for($i = 0; $i < count($path_segments) - 1; $i ++) {
		$dir = $dir . $path_segments[$i] . '/';
		if($mkdir && !file_exists($dir)) {
			mkdir($dir);
		}
	}
	if($path == 'index' && $dir == HTML_DIR)
		$filename = INDEX_FILE;
	else
		$filename = $dir . $path_segments[count($path_segments)-1] . '.html';
	return array($dir, $filename);	
}

function pathfromreq() {
	$path = $_SERVER['PATH_INFO'];
	if($path == null)
		$path = '/index.html';
	return cleanpath($path);
}

function cleanpath($path) {
	if(substr($path, -5) == '.html')
		$path = substr($path, 0, -5);
	if(substr($path, 0, 1) == '/')
		$path = substr($path, 1);
	return $path;
}

function content($path, $prefix) {
	list($dir, $filename) = path2dirfile($path, false);
	$template = file_get_contents(TEMPLATE_FILE);
	$content = file_get_contents($filename);
	list($meta, $content) = parse_content($content);
	$html = str_replace('{CONTENT}', $content, $template);
	$html = str_replace('{EDIT_LINK}', sprintf('<a href="%sedit.php/%s">Edit</a>', $prefix, $path), $html);
	foreach($meta as $key => $value)
		$html = str_replace('{'.$key.'}', $value, $html);
	return $html;
}

function parse_content($content) {
	preg_match_all('@\{([A-Z]+)\s*:\s*(.*?)\}@', $content, $matches, PREG_SET_ORDER);
	$content = preg_replace('@\{([A-Z]+)\s*:\s*(.*?)\}@', '', $content);
	$meta = array();
	foreach($matches as $match) {
		$meta[$match[1]] = $match[2];
	}
	return array($meta, $content);
}